#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
@author:zhengxin
@file: permissions.py
@time: 2022/4/19  14:25
# @describe: 评论权限-所有人可查看，仅本人可更改
"""
from rest_framework.permissions import BasePermission, SAFE_METHODS


class IsOwnerOrReadOnly(BasePermission):
    message = 'You must be the owner to update.'

    def safe_methods_or_owner(self, request, func):
        if request.method in SAFE_METHODS:
            return True
        return func()

    # 对用户登录状态做一个预先检查-验证当前评论的作者和当前登录的用户是否为同一个人
    def has_permission(self, request, view):
        return self.safe_methods_or_owner(request,
                                          lambda: request.user.is_authenticated
                                          )

    def has_object_permission(self, request, view, obj):
        return self.safe_methods_or_owner(
            request,
            lambda: obj.author == request.user
        )